﻿using Admin.Core.Common.Auth;
using Admin.Core.Common.Input;
using Admin.Core.Common.Output;
using Admin.Core.Common.ParamInput;
using Admin.Core.Model.Warehouse;
using Admin.Core.Repository.Warehouse.StockIn;
using Admin.Core.Service.Warehouse.StockList.Output;
using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Admin.Core.Service.Warehouse.StockList
{
    public class StockListService : IStockListService
    {
        private readonly IUser _user;
        private readonly IMapper _mapper;
        //private readonly IStockOutRepository _stockOutRepository;
        private readonly IStockInRepository _stockInRepository;
        //private readonly IXbcMaterrialRepository _xbcMaterrialRepository;
        //private readonly IXbcWarehouseRepository _xbcWarehouseRepository;
        //private readonly IXbcLocationRepository _xbcLocationRepository;
        //private readonly IXbcTypeRepository _xbcTypeRepository;
        public StockListService(IUser user, IMapper mapper
            //, IStockOutRepository stockOutRepository
            , IStockInRepository stockInRepository
            //, IXbcMaterrialRepository xbcMaterrialRepository
            //, IXbcTypeRepository xbcTypeRepository
            //, IXbcWarehouseRepository xbcWarehouseRepository
            //,IXbcLocationRepository xbcLocationRepository
            )
        {
            _user = user;
            _mapper = mapper;
            //_stockOutRepository = stockOutRepository;
            _stockInRepository = stockInRepository;
            //_xbcTypeRepository = xbcTypeRepository;
            //_xbcWarehouseRepository = xbcWarehouseRepository;
            //_xbcLocationRepository = xbcLocationRepository;
            //_xbcMaterrialRepository = xbcMaterrialRepository;
        }

        /// <summary>
        /// 分页查询库存信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<IResponseOutput> PageAsync(PageInput<StockInCkFilterInput> input)
        {
                var key = input.Filter?.WlCode; //物料号
                string filter1 = string.Empty;
                string filter2 = string.Empty;
            if (key.NotNull())
            {
                filter1 = $@"AND((a__XbcMatterrial.CODE)LIKE '%{key}%')";
            }
            var typeId = input.Filter?.Wllb; //物料类别
            if (typeId != null)
            {
                filter2 = $@"AND (a__XbcMatterrial.XBCTYPEID = {typeId})";
            }

            string strsql = $@"SELECT a__XbcMatterrial.CODE MaterrialCode, a__XbcMatterrial.NAME MaterrialName, a__XbcMatterrial__Ckdw.NAME KcDw, sum(a.REMAINNUM) KcNum,
     a__XbcLocation.NAME KwName, a__XbcLocation__XbcWarehouse.NAME CkName, a.XBCMATTERRIALID MatterrialId, a.XBCLOCATIONID LocationId,
      (select sum(f.remainnum) from  ST_STOCKIN f where 
      f.TENANTID = 1 AND f.ISDELETED = 0 and 
      f.xbcmatterrialid=a.xbcmatterrialid and f.xbclocationid = a.xbclocationid 
        and f.effectivedate < SYSDATE
    ) as ExpiredNum
    FROM ST_STOCKIN a
    LEFT JOIN WH_XBC_MATERRIAL a__XbcMatterrial ON a__XbcMatterrial.ID = a.XBCMATTERRIALID
    LEFT JOIN AD_DICTIONARY a__XbcMatterrial__Ckdw ON a__XbcMatterrial__Ckdw.ID = a__XbcMatterrial.CKDWID
    LEFT JOIN WH_XBC_LOCATION a__XbcLocation ON a__XbcLocation.ID = a.XBCLOCATIONID
    LEFT JOIN WH_XBC_WAREHOUSE a__XbcLocation__XbcWarehouse ON a__XbcLocation__XbcWarehouse.ID = a__XbcLocation.XBCWAREHOUSEID
    WHERE (a.TENANTID = {this._user.TenantId} AND a.ISDELETED = 0) AND (a.ISDELETED = 0)  {filter1} {filter2} 
    GROUP BY a.XBCMATTERRIALID, a.XBCLOCATIONID, a__XbcMatterrial.CODE, a__XbcMatterrial__Ckdw.NAME, a__XbcMatterrial.NAME, 
    a__XbcLocation.NAME, a__XbcLocation__XbcWarehouse.NAME";

            var list = await _stockInRepository.Orm.Ado.QueryAsync<StockListOutput>(strsql);

            #region  保留
            //var list = await _stockInRepository.baseRepository.Select
            //.WhereIf(key.NotNull(), a => a.XbcMatterrial.Code.Contains(key))
            //.WhereIf(typeId != null, a => a.XbcMatterrial.XbcTypeId.Equals(typeId))
            //.GroupBy<Tudemo>(x => new Tudemo { MatterrialId = x.XbcMatterrialId, LocationId = x.XbcLocationId, MatterrialCode = x.XbcMatterrial.Code, KcDw = x.XbcMatterrial.Ckdw.Name, MatterrialName = x.XbcMatterrial.Name, LocationCode = x.XbcLocation.Name, CkName = x.XbcLocation.XbcWarehouse.Name })
            //// .Count(out var total)
            ////.Page(input.CurrentPage, input.PageSize)
            //    .ToListAsync((a) => new StockListOutput
            //    {
            //        MaterrialCode = a.Key.MatterrialCode,
            //        MaterrialName = a.Key.MatterrialName,
            //        KcDw = a.Key.KcDw,
            //        KcNum = a.Sum(a.Value.RemainNum),
            //        KwName = a.Key.LocationCode,
            //        CkName = a.Key.CkName,
            //        MatterrialId = a.Key.MatterrialId,
            //        LocationId = a.Key.LocationId
            //    });
            ////,
            ////         ExpiredNum = _stockInRepository.baseRepository.Select.Where(x => x.XbcMatterrialId == a.Value.XbcMatterrialId && x.XbcLocationId == a.Value.XbcLocationId).Sum(x => x.RemainNum)
            #endregion
            var data = new VxePageOutPut<StockListOutput>()
                {
                    Result = list,
                    Page = null //new VxePage { currentPage = input.CurrentPage, pageSize = input.PageSize, total = total, totalResult = total }
                };
                return ResponseOutput.Ok(data);
        }
        /// <summary>
        /// 分页查询库存明细信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<IResponseOutput> PageDetailAsync(PageInput<StockInDetailFilterInput> input)
        {
            var wlId = input.Filter?.wlId; //物料id
            var kwId = input.Filter?.kwId; //库位id
            var list = await _stockInRepository.baseRepository.Select
            .WhereIf(wlId != null, a => a.XbcMatterrialId.Equals(wlId))
            .WhereIf(kwId != null, a => a.XbcLocationId.Equals(kwId))
            .Count(out var total)
            //.OrderByDescending(true, c => c.Id)
            .Page(input.CurrentPage, input.PageSize)
            .ToListAsync((a) => new StockListDetailOutput
            {
                AddStorageBatchCode = a.AddStorageBatchCode,
                 Ckmc = a.XbcLocation.XbcWarehouse.Name,
                  RemainNum = a.RemainNum,
                   WlCode = a.XbcMatterrial.Code,
                    Wlms = a.XbcMatterrial.Name,
                     XbcLocationCode = a.XbcLocation.Name,
                      Dw = a. XbcMatterrial.Ckdw.Name
            });
            var data = new VxePageOutPut<StockListDetailOutput>()
            {
                Result = list,
                Page = new VxePage { currentPage = input.CurrentPage, pageSize = input.PageSize, total = total, totalResult = total }
            };
            return ResponseOutput.Ok(data);
        }

        
        public async Task<List<StockListDetailOutput>> GetAllDetailPageAsync(long? wlId, long? kwId)
        {
            var list = await _stockInRepository.baseRepository.Select
                .WhereIf(wlId != null, a => a.XbcMatterrialId.Equals(wlId))
                .WhereIf(kwId != null, a => a.XbcLocationId.Equals(kwId))
                .ToListAsync((a) => new StockListDetailOutput
                {
                    AddStorageBatchCode = a.AddStorageBatchCode,
                    Ckmc = a.XbcLocation.XbcWarehouse.Name,
                    RemainNum = a.RemainNum,
                    WlCode = a.XbcMatterrial.Code,
                    Wlms = a.XbcMatterrial.Name,
                    XbcLocationCode = a.XbcLocation.Name,
                    Dw = a.XbcMatterrial.Ckdw.Name
                });
            return list;
        }
        public async Task<List<StockListOutput>> GetAllPageAsync(string name, long? xbcTypeId)
        {
            var list = await _stockInRepository.baseRepository.Select
                .WhereIf(name.NotNull(), a => a.XbcMatterrial.Code.Contains(name))
                .WhereIf(xbcTypeId != null, a => a.XbcMatterrial.XbcTypeId.Equals(xbcTypeId))
                .GroupBy<Tudemo>(x => new Tudemo { MatterrialCode = x.XbcMatterrial.Code, MatterrialName = x.XbcMatterrial.Name, LocationCode = x.XbcLocation.Name, CkName = x.XbcLocation.XbcWarehouse.Name })
                .ToListAsync((a) => new StockListOutput
                {
                    MaterrialCode = a.Key.MatterrialCode,
                    MaterrialName = a.Key.MatterrialName
                ,
                    KcNum = a.Sum(a.Value.RemainNum),
                    KwName = a.Key.LocationCode,
                    CkName = a.Key.CkName
                });
            return list;
        }
    }
}
